#pragma once

#include <string>
#include <vector>
#include <mutex>
#include <cassert>
#include <fstream>
#include <algorithm>
#include <jsoncpp/json/json.h>
#include "../comm/httplib.h"
#include "oj_model.hpp"
#include "../comm/util.hpp"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace std;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;

    class Machine
    {
    public:
        std::string ip;  // IP地址
        int port;        // 端口号
        uint64_t load;   // 负载的数量
        std::mutex *mtx; // mutex是不能拷贝的，我们这里使用指针

    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}

    public:
        void InLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }

        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }

        void RestLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }

        uint64_t Load()
        {
            uint64_t ret = 0;
            if (mtx)
                mtx->lock();
            ret = load;
            if (mtx)
                mtx->unlock();

            return ret;
        }
    };

    std::string service_machine = "./conf/service_machine.conf";

    // 负载均衡模块
    class LoadBlance
    {
    private:
        // 可以提供服务的所有主机
        // 每个主机都有下标，小标表示id
        std::vector<Machine> machines;
        // 在线的机器
        std::vector<int> online;
        // 离线的机器
        std::vector<int> offline;

        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
        }
        ~LoadBlance() {}

        bool LoadConf(const std::string &machine_list)
        {
            std::ifstream in(machine_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_list << "失败" << "\n";
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
            std:
                vector<std::string> machine;
                StringUtil::SplitString(line, &machine, ":");

                if (machine.size() != 2)
                {
                    LOG(WARNING) << "配置文件部分加载失败，请检查配置文件的格式" << "\n";
                    continue;
                }

                Machine mch;
                mch.ip = machine[0];
                mch.port = atoi(machine[1].c_str());
                mch.load = 0;
                mch.mtx = new std::mutex;

                online.push_back(machines.size());
                machines.push_back(mch);
            }

            in.close();
            return true;
        }

        // id: 输出型参数
        // m : 输出型参数
        bool SmartChoice(int *id, Machine **m)
        {
            mtx.lock();

            // 轮询查找
            int mch_num = online.size();
            if (mch_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << " 所有的后端编译主机已经离线, 请运维的同事尽快查看"
                           << "\n";
                return false;
            }

            *id = online[0];
            *m = &machines[online[0]];
            Machine min_mch = machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();

            for (int i = 0; i < mch_num; i++)
            {
                uint64_t curren_load = machines[online[i]].load;
                if (min_load > curren_load)
                {
                    min_load = curren_load;
                    min_mch = machines[online[i]];
                    *id = online[i];
                    *m = &min_mch;
                }
            }
            mtx.unlock();
            return true;
        }

        void OfflineMachine(int which)
        {
            mtx.lock();
            for(auto iter=online.begin();iter!=online.end();iter++)
            {
                if(*iter == which)
                {
                    //要离线的主机终找到了
                    online.erase(iter);
                    offline.push_back(which);
                    break;//循环结束了，不用考虑迭代器失效
                }
            }
            mtx.unlock();

        }

        void OnloneMachine()
        {
            mtx.lock();
            online.insert(online.end(),offline.begin(),offline.end());
            offline.erase(offline.begin(),offline.end());
            mtx.unlock();

            LOG(INFO)<<"所有的主机又上线了"<<"\n";
        }

        void ShowMachine()
        {
            mtx.lock();
            std::cout<<"在线的主机有：";
            for(auto& iter:online)
            {
                std::cout<<" "<<iter;
            }
            std::cout<<std::endl;

             std::cout<<"离线的主机有：";
            for(auto& iter:offline)
            {
                std::cout<<" "<<iter;
            }
            std::cout<<std::endl;
            mtx.unlock();
        }
    };

    // 这是我们核心业务逻辑的控制器
    class Control
    {
    private:
        Model model_;             // 提供后台数据
        View view_;               // 提供html渲染功能
        LoadBlance load_balance_; // 平衡控制器

    public:
        Control() {}
        ~Control() {}
        
        void Recovery()
        {
            load_balance_.OnloneMachine();
        }
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<Question> all;
            if (model_.GetAllQuestions(&all))
            {
                sort(all.begin(),all.end(),[](const Question& q1,const Question& q2){
                    return (atoi(q1.number.c_str()) < atoi(q2.number.c_str()));
                });
                // 获取所有题目的网页
                view_.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败, 形成题目列表失败";
                ret = false;
            }
            return ret;
        }

        bool OneQuestion(const string &number, string *html)
        {
            bool ret = true;
            Question q;
            if (model_.GetOneQuestions(number, &q))
            {
                view_.OneExpandHtml(q, html);
            }
            else
            {
                *html = "获取单个题目失败";
                ret = false;
            }
            return ret;
        }

        // id:123
        // code:#include....
        // input:""
        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            // 0.获取题目信息
            Question q;
            model_.GetOneQuestions(number, &q);
            // 1.in_json进行反序列化，得到题目id，得到用户提交源代码，input
            Json::Reader reader;
            Json::Value in_value;

            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();
            // 2.重新拼接用户代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);

            // 3.选择负载最底的主机(差错处理)
            // 一直选择，直到有主机可用，否则就是全部挂机
            while (true)
            {
                int id;
                Machine *m;
                if (!load_balance_.SmartChoice(&id, &m))
                {
                    break;
                }
                // 4.然后发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->InLoad();
                LOG(INFO) << "主机选择成功：" << id << " 详细：" << "ip:" << m->ip << " port:" << m->port <<" load:"<<m->Load() << "\n";
                if (auto res = cli.Post("/complie_and_run", compile_string, "application/json;charset=utf_8"))
                {
                    // 5.*out_json = 将结果赋值给out_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "主机选择失败：" << id << " 详细：" << "ip:" << m->ip << "port:" << m->port << "\n";
                    load_balance_.OfflineMachine(id);
                    load_balance_.ShowMachine();
                }
            }
        }
    };
};